import requests
import json
import pandas as pd

from utils.write_to_excel import write_to_excel  # 修改为从utils包导入
import aiohttp
import asyncio
from utils.utils import convert_json_data


USER_ID = 'abc-123'
# qwen2.5:32b 模型解题
API_KEY = 'app-roa2m5rs5ihVUWtqBWIgkURf'

FILE_NAME = 'assistant-slove.xlsx'


async def send_chat_request(session, query, index, hander=None):
    # 定义请求的URL
    url = 'http://8.136.111.93:8008/v1/chat-messages'
    # 定义请求头
    headers = {
        'Authorization': f'Bearer {API_KEY}',  # 使用宏定义的 API_KEY
        'Content-Type': 'application/json'
    }

    # 定义请求数据
    data = {
        "inputs": {},
        "query": query,
        "response_mode": "blocking",
        "conversation_id": "",
        "user": USER_ID,  # 使用宏定义的 USER_ID
        "files": []
    }

    # 发送POST请求
    try:
        async with session.post(url, headers=headers, data=json.dumps(data)) as response:
            # print(f"当前索引: {index}")
            # 检查响应状态码
            if response.status == 200:
                print("请求成功，返回的数据：")
                response_data = await response.json()

                # 将 answer 单独赋值给新的变量
                answer = response_data.get('answer')  # 假设 'answer' 是返回数据中的一个字段

                # 解析 answer 变量（假设 answer 是一个 JSON 字符串）
                if isinstance(answer, str):  # 确保 answer 是字符串
                    try:
                        parsed_answer = convert_json_data(
                            answer)  # 解析 JSON 字符串

                        # 清理无效转义字符
                        # for key in parsed_answer.keys():
                        #     if isinstance(parsed_answer[key], str):
                        #         # 替换无效的转义字符
                        #         parsed_answer[key] = parsed_answer[key].encode(
                        #             'utf-8').decode('unicode_escape')

                        if callable(hander):
                            parsed_answer = hander(parsed_answer, url)

                        # print("解析 answer 时正确字符串:", answer)
                        # 解构 question 和 answer 字段
                        question = parsed_answer.get(
                            'question')  # 获取 question 字段
                        answer_content = parsed_answer.get(
                            'answer')  # 获取 answer 字段
                        write_to_excel(FILE_NAME, parsed_answer)
                        return answer_content

                    except json.JSONDecodeError as e:
                        print("解析 answer 时出错:", e)
                        print("解析 answer 时出错字符串:", answer)
                else:
                    print("answer 不是一个有效的 JSON 字符串。")

            else:
                print(f"请求失败: {response.status}, 响应内容: {await response.text()}")
                return None  # 返回 None 以指示请求失败
            # 额外的调试信息
            if response.status == 400:
                error_info = await response.json()
                print(
                    f"错误代码: {error_info.get('code')}, 错误信息: {error_info.get('message')}")

    except aiohttp.ClientError as e:
        print(f"请求异常: {e}")
        return None  # 返回 None 以指示请求异常


async def fetch_all(querys, hander=None):
    async with aiohttp.ClientSession() as session:  # 创建异步会话
        responses = []  # 存储所有的响应
        for i in range(0, len(querys), 5):  # 每 5 个问题分一组
            tasks = []  # 存储当前组的请求任务
            # 使用 enumerate 获取原始索引
            for index, query in enumerate(querys[i:i + 5], start=i):
                tasks.append(send_chat_request(
                    session, query, index, hander))  # 添加异步请求任务
            group_responses = await asyncio.gather(*tasks)  # 等待当前组的所有请求完成
            responses.extend(group_responses)  # 将当前组的响应添加到总响应列表
        return responses  # 返回所有响应
